package com.chungkui.check.expression;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author jason
 */
public abstract class BaseMinMaxExpression extends BaseExpression {
    protected Comparable min;
    protected Comparable max;
    protected String param;
    protected String code;
    protected Boolean require;

    public CheckResult checkMinMax(Comparable min, Comparable max, Comparable v) {
        if (min != null && v.compareTo(min) < 0) {
            String msg = MapUtils.getString(this.msg, Constants.MIN, this.normalMsg);
            return CheckResult.fail(this.code, this.param, StringUtils.isEmpty(msg) ? Constants.MIN_OVER : msg, v.toString());
        }
        if (max != null && v.compareTo(max) > 0) {
            String msg = MapUtils.getString(this.msg, Constants.MAX, this.normalMsg);
            return CheckResult.fail(this.code, this.param, StringUtils.isEmpty(msg) ? Constants.MAX_OVER : msg, v.toString());
        }
        return CheckResult.success();
    }

    protected void init(Map<String, Object> config) {
        Object message = MapUtils.getObject(config, Constants.MSG);
        if (message instanceof String) {
            this.msg = Maps.newHashMap();
            this.normalMsg = (String) message;
        } else {
            this.msg = (Map<String, Object>) message;
        }
        this.param = MapUtils.getString(config, "param");
        this.code = MapUtils.getString(config, "code");
        this.require = MapUtils.getBoolean(config, "require", true);
    }

    public void setIntegerMinMax(Map<String, Object> data) {
        this.min = MapUtils.getInteger(data, "min");
        this.max = MapUtils.getInteger(data, "max");
    }

    public Comparable getMin() {
        return min;
    }

    public void setMin(Comparable min) {
        this.min = min;
    }

    public Comparable getMax() {
        return max;
    }

    public void setMax(Comparable max) {
        this.max = max;
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }


}
